package com.DHH.Shiro;

import com.DHH.Config.Constant;
import com.DHH.Entity.Base.BaseUser;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class LoginFilter extends AccessControlFilter {
    final static Class<LoginFilter> CLASS = LoginFilter.class;
    @Override
    protected boolean isAccessAllowed(ServletRequest request,
                                      ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest request1=(HttpServletRequest)request;
        BaseUser baseUser=(BaseUser) request1.getSession().getAttribute(Constant.USER_IDENTIFICATION);
        if (baseUser!=null&&baseUser.getId()!=null) {// &&// isEnabled()
            return Boolean.TRUE;
        }
        if (isAjax(request)) {// ajax请求
            Map<String, String> resultMap = new HashMap<String, String>();
            resultMap.put("login_status", "300");
            resultMap.put("message",
                    "\u5F53\u524D\u7528\u6237\u6CA1\u6709\u767B\u5F55\uFF01");// 当前用户没有登录！
            out(response, resultMap);
        }
        return Boolean.FALSE;
    }
    @Override
    protected boolean onAccessDenied(ServletRequest request,
                                     ServletResponse response) throws Exception {

        return Boolean.FALSE;
    }

    public  boolean isAjax(ServletRequest request){
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if("XMLHttpRequest".equalsIgnoreCase(header)){
            return Boolean.TRUE;
        }
        return Boolean.TRUE;
    }
    public  void out(ServletResponse response, Map<String, String> resultMap){
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");//设置编码
            response.setContentType("application/json");//设置返回类型
            out = response.getWriter();
            out.println(JSONObject.toJSONString(resultMap).toString());//输出
        } catch (Exception e) {

        }finally{
            if(null != out){
                out.flush();
                out.close();
            }
        }
    }
}